import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:system_tray/system_tray.dart';
import 'package:window_manager/window_manager.dart';

/// 初始化托盘
Future<void> initSystemTray(AppWindow appWindow) async{
  // 创建右键菜单
  final SystemTray systemTray = SystemTray();
  // 获取图标路径
  String iconPath = await getIconPath();
  await systemTray.initSystemTray(
    iconPath: iconPath,
    toolTip: '我的Flutter应用',
  );
  final Menu menu = Menu();
  await menu.buildFrom([
    MenuItemLabel(
      label: '设置',
      onClicked: (menuItem) {
      },
    ),
    MenuItemLabel(
      label: '退出',
      onClicked: (menuItem) {
        appWindow.close();
        exit(0);
      },
    ),
  ]);
  
  // 设置菜单
  await systemTray.setContextMenu(menu);
  // 设置点击事件
  systemTray.registerSystemTrayEventHandler((eventName) {
    if (eventName == 'right-click') {
      systemTray.popUpContextMenu();
      appWindow.show();
    }
  });

}

/// 初始化窗口
Future<void> initWindow() async{
  await windowManager.ensureInitialized();

  WindowOptions windowOptions = WindowOptions(
    skipTaskbar: true, // 窗口不在任务栏显示
    titleBarStyle: TitleBarStyle.hidden,//隐藏标题栏
    alwaysOnTop: false,//窗口不总是置顶
  );

  await windowManager.waitUntilReadyToShow(windowOptions, () async {
    await windowManager.show();
    // await _setWindowToDesktopLevel();
  });
}

/// 获取图标路径
Future<String> getIconPath() async {
  // 根据平台选择图标文件扩展名
  String assetPath = Platform.isWindows 
      ? 'assets/images/test.ico' 
      : 'assets/images/test.png';
  
  // 加载资源数据
  final ByteData byteData = await rootBundle.load(assetPath);
  
  // 获取临时目录
  final Directory tempDir = await getTemporaryDirectory();
  final String tempPath = '${tempDir.path}/tray_icon.${Platform.isWindows ? 'ico' : 'png'}';
  
  // 将资源写入临时文件
  final File file = File(tempPath);
  await file.writeAsBytes(byteData.buffer.asUint8List(
    byteData.offsetInBytes, 
    byteData.lengthInBytes
  ));
  
  if (kDebugMode) {
    print('图标已保存到: $tempPath');
  }
  
  return file.path;
}

// 设置窗口到桌面级别
Future<void> _setWindowToDesktopLevel() async {
  if (Platform.isWindows) {
    // Windows平台：使用FFI调用Win32 API
    await _setWindowsDesktopLevel();
  } else if (Platform.isMacOS) {
    // macOS平台设置
    await _setMacOSDesktopLevel();
  } else if (Platform.isLinux) {
    // Linux平台设置
    await _setLinuxDesktopLevel();
  }
}

// Windows平台实现
Future<void> _setWindowsDesktopLevel() async {
  // 使用window_manager的方法设置窗口层级
  try {
    // 设置窗口为桌面级别
    await windowManager.setAlwaysOnBottom(true);
    
    // 设置点击穿透，让鼠标事件可以到达桌面
    await windowManager.setIgnoreMouseEvents(true);
  } catch (e) {
    if (kDebugMode) {
      print('设置Windows桌面级别失败: $e');
    }
  }
}

// macOS平台实现
Future<void> _setMacOSDesktopLevel() async {
  try {
    // macOS上的实现可能不同
    await windowManager.setAlwaysOnBottom(true);
    await windowManager.setIgnoreMouseEvents(true);
  } catch (e) {
    if (kDebugMode) {
      print('设置macOS桌面级别失败: $e');
    }
  }
}

// Linux平台实现
Future<void> _setLinuxDesktopLevel() async {
  try {
    await windowManager.setAlwaysOnBottom(true);
    await windowManager.setIgnoreMouseEvents(true);
  } catch (e) {
    if (kDebugMode) {
      print('设置Linux桌面级别失败: $e');
    }
  }
}
